package com.hnas.account.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hnas.account.dao.AccountDAO;
import com.hnas.account.orm.Account;
import com.hnas.common.domain.CommonStatus;
import com.hnas.common.outdto.DTOTokenChecked;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.ResultCode;

@Component("accountService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountDAO accountDAO;

	@Override
	public Account findByOpenId(String openId) {
		return this.accountDAO.findByOpenId(openId);
	}

	@Override
	public Account findByPhoneNo(String phoneNo) {
		return accountDAO.findByPhoneNo(phoneNo);
	}

	@Override
	public void unBindOpenid(String openId) {
		accountDAO.unBindOpenid(openId);
	}

	@Override
	public void updateOpenIdAndTime(String id, String openId, String updateTime, String appid) {
		accountDAO.updateOpenIdAndTime(id, openId, updateTime, appid);
	}

	@Override
	public Account saveOrUpdate(Account vo) throws Exception {
		return accountDAO.saveOrUpdate(vo);
	}

	@Override
	public void unBindAccountById(String accountId) {
		accountDAO.unBindAccountById(accountId);
	}

	@Override
	public void unBindAndBindAndUpdateTimeBack(String unBindOpenId, String updateTime, String accountId) {
		accountDAO.unBindOpenid(unBindOpenId);
		accountDAO.bindAcountById(accountId, unBindOpenId);
		// accountDAO.updateTimeBack(accountId,updateTime);
	}

	@Override
	public Account findById(String id) {
		return accountDAO.findById(id);
	}

	@Override
	public String checkedToken(DTOTokenChecked dto) {
		Account account = null;
		account = accountDAO.checkedWXXNKTokenIsExist(dto.getOpenid(), dto.getToken());
		// token不存在
		if (null == account) {
			return ResultCode.ERROR_90009;
		}
		account = accountDAO.checkedWXXNKTokenOverTime(dto.getOpenid(), dto.getToken());
		if (null == account) {
			return ResultCode.ERROR_30005;
		}
		return ResultCode.SUCCESS;
	}

	@Override
	public Account findByEmpId(String empId) {
		return accountDAO.findByEmpId(empId);
	}

	@Override
	public Account modifyPhoneNo(String phoneNo, Account oldAccount, Account newAccount) {
		// 1、逻辑删除合并账户
		oldAccount.setValid(CommonStatus.FALSE);
		accountDAO.saveOrUpdate(oldAccount);
		// 2、绑定账户，修改token值，提示重新登录，返回最新账户
		newAccount.setPhoneNo(phoneNo);
		newAccount.setWxToken(CommonUtils.getNewToken());
		newAccount.setAppToken(CommonUtils.getNewToken());
		newAccount.setOpenId(oldAccount.getOpenId());
		newAccount.setMergeAccId(oldAccount.getId());
		accountDAO.saveOrUpdate(newAccount);
		return newAccount;
	}

}
